package org.hive.vmware.client.ui;

import java.util.Arrays;

import org.hive.vmware.client.model.VmCenterServerTreeFolder;
import org.hive.vmware.client.service.CachedVmwareService;

import com.extjs.gxt.ui.client.Style.HorizontalAlignment;
import com.extjs.gxt.ui.client.data.ModelData;
import com.extjs.gxt.ui.client.store.TreeStore;
import com.extjs.gxt.ui.client.widget.ContentPanel;
import com.extjs.gxt.ui.client.widget.Info;
import com.extjs.gxt.ui.client.widget.LayoutContainer;
import com.extjs.gxt.ui.client.widget.grid.ColumnConfig;
import com.extjs.gxt.ui.client.widget.grid.ColumnModel;
import com.extjs.gxt.ui.client.widget.layout.FitLayout;
import com.extjs.gxt.ui.client.widget.layout.FlowLayout;
import com.extjs.gxt.ui.client.widget.treegrid.TreeGrid;
import com.extjs.gxt.ui.client.widget.treegrid.TreeGridCellRenderer;
import com.google.gwt.user.client.Element;
import com.google.gwt.user.client.rpc.AsyncCallback;

public class BrowseVMsPanel extends LayoutContainer {
	
	private final CachedVmwareService vmWareService = CachedVmwareService.getInstance();
	private TreeStore<ModelData> store;
	
	@Override
	protected void onRender(Element parent, int index) {		
	    super.onRender(parent, index);
	    createPanel(new VmCenterServerTreeFolder("root"));
	    loadModel();
	  }

	private void createPanel(VmCenterServerTreeFolder model) {
		
		setLayout(new FlowLayout(10));
	    store = new TreeStore<ModelData>();
	    store.add(model.getChildren(), true);
	    
	    ColumnConfig name = new ColumnConfig("name", "Name", 250);
	    name.setRenderer(new TreeGridCellRenderer<ModelData>());
	    
	    ColumnConfig groupNameColumn = new ColumnConfig("groupMember", "Group Name", 150);
	    
	    ColumnModel cm = new ColumnModel(Arrays.asList(name, groupNameColumn));

	    ContentPanel cp = new ContentPanel();
	    cp.setBodyBorder(false);
	    cp.setHeading("Browse VM Center Servers - Hosts - VMs");
	    cp.setButtonAlign(HorizontalAlignment.CENTER);
	    cp.setLayout(new FitLayout());
	    cp.setFrame(true);
	    cp.setSize(700, 470);

	    TreeGrid<ModelData> tree = new TreeGrid<ModelData>(store, cm);
	    tree.setBorders(true);
	    //tree.getStyle().setLeafIcon(Resources.ICONS.music());
	    tree.setTrackMouseOver(false);

	    cp.add(tree);

	    add(cp);
	}

	public void loadModel() {
		vmWareService.loadVmCenterFolder(new AsyncCallback<VmCenterServerTreeFolder>(){

			@Override
			public void onFailure(Throwable caught) {
				Info.display("Browse VMs", "Error while loading data.");
			}

			@Override
			public void onSuccess(VmCenterServerTreeFolder result) {
				if (result.isLoadError()) {
					Info.display("Browse VMs", "Error while loading data.");	
				} else {
					store.removeAll();
					store.add(result.getChildren(), true);
				}
			}});
	}
}
